﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AppService.Extension
{
    public static class EncryptExtension
    {
        /// <summary>
        ///  将字符串使用base64算法编码 
        /// </summary>
        /// <param name="source">待加密的字符串</param>
        /// <param name="encodingName">编码类型（编码名称）</param>
        /// <returns>加密后的字符串</returns> 
        public static string EncodeBase64String(this string source, string encodingName = "UTF-8")
        {
            byte[] bytes = Encoding.GetEncoding(encodingName).GetBytes(source);
            return Convert.ToBase64String(bytes);
        }

        /// <summary> 
        /// 将字符串使用base64算法解码
        /// </summary> 
        /// <param name="encodingName">编码类型</param> 
        /// <param name="base64String">已用base64算法加密的字符串</param> 
        /// <returns>解密后的字符串</returns> 
        public static string DecodeBase64String(this string base64String, string encodingName = "UTF-8")
        {
            byte[] bytes = Convert.FromBase64String(base64String);
            return Encoding.GetEncoding(encodingName).GetString(bytes);
        }
        /// <summary>
        /// 将字符串进行MD5
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string EncodeMd5String(this string source)
        {
            if (string.IsNullOrEmpty(source))
                return source;
            var md5 = MD5.Create();
            var result = md5.ComputeHash(Encoding.Default.GetBytes(source));
            return BitConverter.ToString(result).Replace("-", "");
        }

    }
}
